package com.fzfnn.scrapbook.util;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

public class ImageCompressUtil {

    static {
        // 注册 TwelveMonkeys 插件
        ImageIO.scanForPlugins();
    }

    /**
     * 判断文件是否超过 2MB，需要压缩
     */
    public static boolean shouldCompress(long fileSize) {
        return fileSize > 2 * 1024 * 1024;
    }

    /**
     * 强制固定尺寸压缩为 WebP（适合头像）
     */
    public static void compressFixedSize(InputStream inputStream, File outputFile, double quality, int width, int height, String format) throws IOException {
        BufferedImage inputImage = ImageIO.read(inputStream);

        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, width, height, null);
        g2d.dispose();

        try (OutputStream os = new FileOutputStream(outputFile)) {
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(format);
            if (!writers.hasNext()) throw new IllegalStateException("No writer found for format: " + format);

            ImageWriter writer = writers.next();
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

                // ✅ 修复：设置压缩类型
                String[] compressionTypes = param.getCompressionTypes();
                if (compressionTypes != null && compressionTypes.length > 0) {
                    param.setCompressionType(compressionTypes[0]);  // 一般为 "Lossy" 或 "Lossless"
                }

                param.setCompressionQuality((float) quality);  // 0.0 到 1.0
            }

            writer.write(null, new IIOImage(resizedImage, null, null), param);
            ios.close();
            writer.dispose();
        }
    }



    /**
     * 最大边等比压缩（适合手账图），并转换为 WebP
     */
    public static void compressAndConvertToWebp(InputStream inputStream, File destFile, float quality, int maxLength) throws IOException {
        BufferedImage originalImage = ImageIO.read(inputStream);
        if (originalImage == null) {
            throw new IOException("无法读取输入图像");
        }

        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        float scale = (width > height) ? ((float) maxLength / width) : ((float) maxLength / height);
        if (scale > 1) scale = 1;

        int newWidth = Math.round(width * scale);
        int newHeight = Math.round(height * scale);

        Image scaledImage = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage outputImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(scaledImage, 0, 0, null);
        g2d.dispose();

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(destFile)) {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("webp").next();
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }

            writer.write(null, new IIOImage(outputImage, null, null), param);
            writer.dispose();
        }
    }

    /**
     * 将图片转换为 WebP 格式（不压缩尺寸）
     */
    public static void convertToWebp(InputStream inputStream, File destFile, float quality) throws IOException {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            throw new IOException("无法读取输入图像");
        }

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(destFile)) {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("webp").next();
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }

            writer.write(null, new IIOImage(image, null, null), param);
            writer.dispose();
        }
    }
    /**
     * 自动判断是否压缩并转为 WebP（适合 scrapbook 图）
     */
    public static void autoCompressToWebp(InputStream inputStream, File destFile, long originalSize, float quality, int maxLength) throws IOException {
        if (originalSize > 2 * 1024 * 1024) {
            compressAndConvertToWebp(inputStream, destFile, quality, maxLength);
        } else {
            convertToWebp(inputStream, destFile, 1.0f);
        }
    }

}
